import { cbtPrint } from "hy-algokit";
import IHeap from "./IHeap";

class Heap<T> implements IHeap<T> {
  private _data: T[] = [];
  private _size: number = 0;

  private swap(i: number, j: number): void {
    const temp = this._data[i];
    this._data[i] = this._data[j];
    this._data[j] = temp;
  }

  insert(value: T): void {
    this._data.push(value);
    this._size++;

    let index = this._size - 1;

    while (index > 0) {
      const parentIndex = Math.floor((index - 1) / 2);
      // 如果当前节点比父节点小，则不需要交换位置
      if (this._data[index] <= this._data[parentIndex]) {
        break;
      }
      // 如果当前节点比父节点大，则交换位置
      if (this._data[index] > this._data[parentIndex]) {
        this.swap(index, parentIndex);
        index = parentIndex;
      }
    }
  }
  extract(): T | undefined {
    return undefined;
  }
  peek(): T | undefined {
    return this._data[0];
  }
  isEmpty(): boolean {
    return this._size === 0;
  }
  get length(): number {
    return this._size;
  }
  build_heap(array: T[]): void {}
  print(): void {
    cbtPrint(this._data);
  }
}

const arr = [19, 100, 36, 17, 3, 25, 1, 2, 7];
const heap = new Heap<number>();

arr.forEach((item) => {
  heap.insert(item);
});

heap.print();

export {};
